"""
Author: miaokela
Date: 2024-02-29 17:44:18
LastEditTime: 2024-03-01 14:15:30
"""
import os
from lxml import etree

class ResetProject(object):
    """
    根据指定配置参数将项目初始化
        artifactId
        groupId
    """

    def __init__(self, group_id="quickstart", artifact_id="springboot-demo"):
        self.group_id = group_id
        self.artifact_id = artifact_id
        self.project_path = self.get_project_path()

    def get_project_path(self):
        """
        获取当前执行文件的路径
        """
        return os.path.dirname(os.path.abspath(__file__))

    def replace_in_file(self, file_path, old_str, new_str):
        """
        将文件中old_str文本都替换成new_str
        """
        with open(file_path, 'r', encoding='utf-8') as file:
            filedata = file.read()
        filedata = filedata.replace(old_str, new_str)
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(filedata)

    def replace_in_dir(self, dir_path, old_str, new_str):
        """
        将所有文件夹名称为old_str,都修改成new_str
        """
        for root, dirs, files in os.walk(dir_path, topdown=False):
            for name in files:
                file_path = os.path.join(root, name)
                # print(f'将文件 {file_path} 内容 {old_str} 修改成 {new_str}')
                self.replace_in_file(file_path, old_str, new_str)
            for name in dirs:
                if old_str in name:
                    # print(f'将文件名 {os.path.join(root, name)} 替换成 {os.path.join(root, name.replace(old_str, new_str))}')
                    os.rename(os.path.join(root, name), os.path.join(root, name.replace(old_str, new_str)))

    def replace_in_pom(self):
        """
        project节点下<groupId></groupId>节点文本替换成com.{group_id}
        project节点下<artifactId></artifactId>节点文本替换成{artifact_id}
        """
        pom_path = os.path.join(self.project_path, 'pom.xml')
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(pom_path, parser)
        root = tree.getroot()
        namespace = {'maven': 'http://maven.apache.org/POM/4.0.0'}
        
        groupId = root.find('.//maven:groupId', namespaces=namespace)
        if groupId is not None:
            groupId.text = f"com.{self.group_id}"
        
        artifactId = root.find('.//maven:artifactId', namespaces=namespace)
        if artifactId is not None:
            artifactId.text = self.artifact_id
        
        tree.write(pom_path, pretty_print=True, xml_declaration=True, encoding='utf-8')

    def run(self):
        """
        执行替换操作
        """
        _dirs = [
            os.path.join(self.project_path, 'src/main/java'),
            os.path.join(self.project_path, 'src/test/java'),
        ]
        for _dir in _dirs:
            self.replace_in_dir(_dir, 'quickstart', self.group_id)
            # self.replace_in_dir(_dir, 'miaokela', self.group_id)
            # self.replace_in_dir(_dir, 'springboot-demo', self.artifact_id)
        self.replace_in_pom()

if __name__ == '__main__':
    rp = ResetProject(group_id="miaokela", artifact_id="myproject")
    rp.run()
